//
//  PPImageFlowViewController.m
//  pickpic
//
//  Created by Jinxiao on 9/4/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPImageFlowViewController.h"

#import "PPAbstractPictureViewController.h"

@interface PPImageFlowCell ()
@property (readwrite, nonatomic, strong) UIButton *selectButton;
@property (readwrite, nonatomic, strong) UIImageView *imageView;
@property (readwrite, nonatomic, assign) BOOL editing;
@end

@interface PPImageFlowViewController () <UICollectionViewDelegateFlowLayout, PPImageFlowCellDelegate>
@property (readwrite, nonatomic, strong) UICollectionView *collectionView;
@property (readwrite, nonatomic, strong) UIView *emptyPromptView;
@end

@implementation PPImageFlowViewController

- (void)viewDidLoad {
    [super viewDidLoad];

//    self.automaticallyAdjustsScrollViewInsets = YES;
//    self.edgesForExtendedLayout = UIRectEdgeTop;

    _editing = YES;

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;

    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    [_collectionView registerClass:[PPImageFlowCell class] forCellWithReuseIdentifier:@"cell"];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.alwaysBounceVertical = YES;
    [self.view addSubview:_collectionView];

    if (@available(iOS 11.0, *)){
        _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    _collectionView.frame = self.view.bounds;

//    _collectionView.frame = CGRectMake(0,0, self.view.width, self.view.height);
}


- (void)reloadData {
    [_collectionView reloadData];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width = (collectionView.width - 3)/4;

    return CGSizeMake(width, width);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 1;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

    ((PPImageFlowCell *)cell).item = [_items safeObjectAtIndex:indexPath.row];
    ((PPImageFlowCell *)cell).editing = _editing;
    ((PPImageFlowCell *)cell).delegate = self;

    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if(_items.count == 0) {
        UIView *emptyPromptView = [self emptyPromptViewForError:nil];
        self.emptyPromptView = emptyPromptView;
    } else {
        self.emptyPromptView = nil;
    }

    return _items.count;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if([_delegate respondsToSelector:@selector(flowViewController:didSelectFlowItem:atIndex:)]) {
        NSInteger index = indexPath.row;

        PPImageFlowItem *flowItem = [self.items safeObjectAtIndex:index];

        [_delegate flowViewController:self didSelectFlowItem:flowItem atIndex:index];
    } else {

        PPAbstractPictureViewController *pictureViewController = [[PPAbstractPictureViewController alloc] init];

        NSMutableArray *artworks = [NSMutableArray array];

        for(PPImageFlowItem *flowItem in self.items) {
            PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
            artwork.image = flowItem.image;
            artwork.URLString = flowItem.URLString;
            [artworks addObject:artwork];
        }

        pictureViewController.index = indexPath.row;
        pictureViewController.artworks = artworks;

        [self.navigationController pushViewController:pictureViewController animated:YES];
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (void)imageFlowCell:(PPImageFlowCell *)imageFlowCell didChangeSelection:(BOOL)selection forImageFlowItem:(PPImageFlowItem *)imageFlowItem {
    [self selectedItemsDidChanged];
}

#pragma mark -

- (void)setEditing:(BOOL)editing {
    _editing = editing;

    [_items enumerateObjectsUsingBlock:^(PPImageFlowItem *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
        obj.selected = NO;
    }];

    [_collectionView reloadData];
}

- (void)selectedItemsDidChanged {

}

- (void)setEmptyPromptView:(UIView *)emptyPromptView {
    if(_emptyPromptView == emptyPromptView) {
        return;
    }

    if(_emptyPromptView != nil) {
        [_emptyPromptView removeFromSuperview];
        _emptyPromptView = nil;
    }

    if(emptyPromptView != nil) {
        _emptyPromptView = emptyPromptView;

        [_collectionView addSubview:_emptyPromptView];

        [_emptyPromptView mas_makeConstraints:^(MASConstraintMaker *make) {
            CGPoint center = [self preferredEmptyPromptViewCenter];
            make.centerX.equalTo(_collectionView.mas_leading).offset(center.x);
            make.centerY.equalTo(_collectionView.mas_top).offset(center.y);
        }];
    }
}

- (UIView *)emptyPromptViewForError:(NSError *)error {
    return nil;
}


- (CGPoint)preferredEmptyPromptViewCenter {
    return CGPointMake(_collectionView.width/2, _collectionView.height*0.336);
}

@end

@interface PPImageFlowCell ()
@property (readwrite, nonatomic, strong) UIImageView *statusView;
@end

@implementation PPImageFlowCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];

    _imageView = [[UIImageView alloc] init];
    _imageView.backgroundColor = [UIColor colorWithRGBHex:0xF2F2F2];
    _imageView.contentMode = UIViewContentModeScaleAspectFill;
    _imageView.clipsToBounds = YES;
    [self.contentView addSubview:_imageView];

    _statusView = [[UIImageView alloc] init];
//    _statusView.backgroundColor = [UIColor clearColor];
    _statusView.backgroundColor = [UIColor colorWithHexString:@"#F9F9F9"];
    _statusView.image = [UIImage imageNamed:@"shen"];
    [_statusView sizeToFit];
    [self.contentView addSubview:_statusView];

    _selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _selectButton.adjustsImageWhenHighlighted = NO;
    _selectButton.contentEdgeInsets = UIEdgeInsetsMake(6, 6, 6, 6);
    [_selectButton setImage:[UIImage imageNamed:@"radio-white-44"] forState:UIControlStateNormal];
    [_selectButton setImage:[UIImage imageNamed:@"radio-yellow-44"] forState:UIControlStateHighlighted|UIControlStateSelected];
    [_selectButton setImage:[UIImage imageNamed:@"radio-yellow-44"] forState:UIControlStateSelected];
    [_selectButton sizeToFit];
    [_selectButton addTarget:self action:@selector(selectButtonDidPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:_selectButton];

    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    _imageView.frame = self.contentView.bounds;

    _statusView.center = CGPointMake(self.contentView.width/2, self.contentView.height/2);
    
    _selectButton.top = 0;
    _selectButton.right = self.contentView.width;

    _selectButton.hidden = !_editing;
    _selectButton.selected = _item.selected;
}

- (void)selectButtonDidPressed:(UIButton *)button {
    button.selected = !button.selected;

    _item.selected = button.selected;

    [_delegate imageFlowCell:self didChangeSelection:_item.selected forImageFlowItem:_item];
}

- (void)setEditing:(BOOL)editing {
    _editing = editing;

    [self setNeedsLayout];
}

- (void)setItem:(PPImageFlowItem *)item {
    _item = item;

    _statusView.hidden = YES;

    if(item.image != nil) {
        _imageView.image = item.image;
        [self setNeedsLayout];
    } else if(item.URL != nil) {
        [_imageView sd_setImageWithURL:item.URL placeholderImage:nil options:SDWebImageRetryFailed completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            if(error.code == 404) {
                _statusView.hidden = NO;
            }
        }];
    } else if(item.URLString != nil) {
        
        
        [_imageView sd_setImageWithURL:[NSURL URLWithString:item.URLString] placeholderImage:nil options:SDWebImageRetryFailed completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            if(error.code == 404) {
                _statusView.hidden = NO;
            }
        }];
    }
}

@end

@implementation PPImageFlowItem


@end
